package cn.wzr.controller;

import cn.wzr.dao.impl.CommodityDao;
import cn.wzr.entity.Commodity;
import cn.wzr.global.Const;
import cn.wzr.util.CommonTools;
import cn.wzr.util.upload.UploadImageStrategy;
import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;

@WebServlet(Const.WEBURL_SEPARATOR + Const.ACT_MULTCMDTS_VALIDATE)
@MultipartConfig
public class MultiCmdtsValidate extends HttpServlet {

    @SuppressWarnings({ "unchecked", "unchecked" })
	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws IOException {

        Object obj = JSONValue.parse(request.getParameter("cmdtsJsonAry"));
        JSONArray bcJsonAry = (JSONArray)obj;

        String contextPath = getServletContext().getRealPath(String.valueOf(Const.WEBURL_SEPARATOR));
        // 获得数据库操作的DAO
        CommodityDao commodityDao = CommonTools.getCommodityDao(contextPath);
        JSONObject resultJsonObject = new JSONObject();
        String cmdtLineStr="";
        try {
        	JSONArray cmdtJsonAry = new JSONArray();
            for(Object cmdtLine : bcJsonAry){
                cmdtLineStr = cmdtLine.toString().trim();
                JSONObject cmdtJson = new JSONObject();
                Commodity newCmdt = new Commodity(cmdtLineStr); 
                Commodity oldCmdt = commodityDao.getByBarCode(newCmdt.getCmdtSN());
                
                // 路径规则为: 上传根/图片/年份/款号/ (例: /upload/image/2017/17219-80/)
            	// 保存图片的文件夹名,例:"17219-80/"
            	String imgUploadFolderName = newCmdt.getStyleNo();
            	UploadImageStrategy uploadImageStrategy = new UploadImageStrategy(contextPath);
            	// 上传的相对路径,例: upload/image/2017/17219-80/
            	String imgUploadRelativePath = uploadImageStrategy.getUploadRelativePath(imgUploadFolderName);
            	
                short cmdtExist = 0;	// 商品是否已存在
                // 生成json数据{商品对象,上传保存路径,异常描述}.
                if(null == oldCmdt){
                	// 文件不存在,可以上传
                	cmdtExist = 1;
                }
                else{
                    if(oldCmdt.imgFilesIsValid(contextPath)){
                        // 文件存在, 图像可读, 大小不为0, 扩展名不为空
                    	JSONObject cmdtObj = cmdtObjToJSON(oldCmdt);
                        cmdtJson.put(Const.JSP_P_CMDT_OBJ,cmdtObj);
                        cmdtJson.put(Const.JSP_P_CMDT_IMAGEFOLDER,imgUploadRelativePath);
                        cmdtJson.put(Const.JSP_P_CMDT_EXCPINFO,"图片已存在");
                        cmdtExist = 5;
                    }
                    else{ // 文件存在,无图像
                    	cmdtExist = 2;
                    }
                }
                
                if(cmdtExist > 0 && cmdtExist < 5){
                	// 图片路径不存在或路径指向了空文件, 则可以上传图片文件
                	
                	JSONObject cmdtObj = cmdtObjToJSON(newCmdt);
                	cmdtJson.put(Const.JSP_P_CMDT_OBJ,cmdtObj);
                	cmdtJson.put(Const.JSP_P_CMDT_IMAGEFOLDER,imgUploadRelativePath);
                	cmdtJson.put(Const.JSP_P_CMDT_EXCPINFO,"");
                	
                }
                cmdtJsonAry.add(cmdtJson);
            }
            resultJsonObject.put(Const.JSP_P_CMDT_JSONARRAY,cmdtJsonAry);    // 校验后生成的结果数组
            
		} catch(ArrayIndexOutOfBoundsException e){
            System.out.println("发生异常, 商品:" + cmdtLineStr);
            // log.debug
            resultJsonObject.put("errInfo","发生异常, 商品信息:" + cmdtLineStr);
		}
        catch (Exception e) {
        	resultJsonObject.put("errInfo","发生异常," + e.getMessage() + "\n商品信息:" + cmdtLineStr);
		}
        finally{
        	PrintWriter out = response.getWriter();
        	out.print(resultJsonObject);
        }
        
    }


	private JSONObject cmdtObjToJSON(Commodity commodity) {
		JSONObject cmdtObj = new JSONObject();
		cmdtObj.put(Const.JSP_P_CMDT_BARCODE, commodity.getCmdtSN());
		cmdtObj.put(Const.JSP_P_CMDT_STYLENO, commodity.getStyleNo());
		cmdtObj.put(Const.JSP_P_CMDT_CMDTNAME, commodity.getName());
		cmdtObj.put(Const.JSP_P_CMDT_SHOWNO, commodity.getShowNo());
		cmdtObj.put(Const.JSP_P_CMDT_IMAGEPATH, commodity.getImagePath());
		return cmdtObj;
	}


    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request,response);
    }
}
